package com.example.youzhengyang

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import androidx.navigation.fragment.findNavController
import androidx.room.Room
import com.example.youzhengyang.databinding.FragmentAddWordBinding
import kotlinx.coroutines.launch

class AddWordFragment : Fragment() {
    private var _binding: FragmentAddWordBinding? = null
    private val binding get() = _binding!!
    private lateinit var db: WordDatabase

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = FragmentAddWordBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        db = Room.databaseBuilder(
            requireContext(),
            WordDatabase::class.java,
            "word_database"
        ).build()

        binding.buttonSave.setOnClickListener {
            val wordText = binding.editTextWord.text.toString()
            if (wordText.isNotBlank()) {
                viewLifecycleOwner.lifecycleScope.launch {
                    db.wordDao().insert(Word(word = wordText))
                    findNavController().navigateUp()
                }
            }
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
} 